package com.css.util;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Dbj
 * @date 2024年09月13日  18:50
 */
public class MapToEntityUtil {

    public static <T> T mapToEntity(HashMap<String, Object> map, Class<T> entityClass) throws Exception {
        T entity = entityClass.newInstance();

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String fieldName = entry.getKey();
            Object value = entry.getValue();

            Field field = entityClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            if(value == null || "".equals(value)){
                continue;
            }
            if (value instanceof BigDecimal || value instanceof String || value instanceof Double || value instanceof Integer || value instanceof Date) {
                // 如果value是String，转换为BigDecimal
                if (value instanceof String) {
                    // 正确设置字段
                    value = value.toString();
                }
                // 如果value是double，转换为BigDecimal
                else if (value instanceof Double || value instanceof Integer) {
                    value = new BigDecimal( value.toString());
                }
                // 如果value是Date，转换为Date
                else if (value instanceof Date) {
                    value = new Date( value.toString());
                }
                field.set(entity, value);
            } else {
                throw new IllegalArgumentException("The value is not a BigDecimal or cannot be converted.");
            }
        }

        return entity;
    }
}
